import frappe
from frappe import __version__ as frappe_version
from frappe.utils import cstr, flt
from erpnext.stock import stock_balance

def custom_get_ordered_qty(item_code, warehouse):
	ordered_qty = frappe.db.sql(
		"""
		select sum((po_item.qty - po_item.received_qty)*po_item.conversion_factor)
		from `tabPurchase Order Item` po_item, `tabPurchase Order` po
		where po_item.item_code=%s and po_item.warehouse=%s
		and po_item.qty > po_item.received_qty and po_item.parent=po.name
		and po.status not in ('Closed', 'Delivered') and po.docstatus=1
		and po_item.delivered_by_supplier = 0""",
		(item_code, warehouse),
	)

	subcontract_qty = frappe.db.sql(
		"""
		select sum((po_item.qty - po_item.received_qty)*po_item.conversion_factor)
		from `tabSubcontracting Order Item` po_item, `tabSubcontracting Order` po
		where po_item.item_code=%s and po_item.warehouse=%s
		and po_item.qty > po_item.received_qty and po_item.parent=po.name
		and po.status not in ('Closed', 'Delivered') and po.docstatus=1
		""",
		(item_code, warehouse),
	)
	subcontract_qty = flt(subcontract_qty[0][0]) if subcontract_qty else 0
	ordered_qty = flt(ordered_qty[0][0]) if ordered_qty else 0

	return subcontract_qty + ordered_qty

is_frappe_above_v13 = int(frappe_version.split('.')[0]) > 13

if is_frappe_above_v13:
	stock_balance.get_ordered_qty = custom_get_ordered_qty